package com.yc.framework.bizClass;

import com.yc.framework.baseClass.R;
import com.yc.framework.utils.IntUtil;
import com.yc.framework.utils.StringUtil;
import com.yc.system.entity.Book;
import com.yc.system.service.IBookService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: 文件上传下载控制器
 * @Description:上传下载文件控制器
 * @author: 优驰科技-老顾
 * @date: 2018-4-27 上午11:51:40
 * @Copyright: 2018 www.youchisoft.com Inc. All rights reserved.
 * 注意：本内容仅限于优驰软件科技无锡有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@RestController
public class FileUploadController {
    @Value("${file.upload.path}")
    private String path;
    @Value("${file.upload.relativePath}")
    private String relativePath;

    @Autowired
    IBookService iBookService;

    /**
     * 异步请求方式上传文件:请求路径为"/upload"
     *
     * @return 文件保存位置的相对路径
     */
    @PostMapping("index/upload/{bookId}")
    public R upload(MultipartFile file, @PathVariable int bookId) {
        System.out.println("upload");
        try {
            if (null != file) {
                String originalFileName = file.getOriginalFilename();//原始文件名
                if(originalFileName==null){return R.err("文件名错误！");}
                String name = String.format("%s%s", UUID.randomUUID().toString().toLowerCase(),
                        originalFileName.substring(originalFileName.lastIndexOf(".")));
                //a1f974da-0443-46cb-827c-259f2459dee8.docx
//                name=originalFileName.substring(0,originalFileName.lastIndexOf('.'))+name;
                String path = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
                String pathName = path + name;
                String realPath = this.path + path;
                String reqFullFileName = this.relativePath + pathName;
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File f = new File(realPath, name);
                file.transferTo(f);//写入文件

//                业务逻辑
            //  返回bookId以及coverPhoto
                return iBookService.uploadCoverPhoto(bookId,reqFullFileName);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.err("上传失败");
    }

    //http://121.40.42.37:2500/download
    // ?fullFileName=2022/12/1/cva3f675d9-ed7e-46ac-97bf-4fd9bdc6ba62.pdf  （上面返回的地址）
    // &fileName=WEB.pdf      （下载后的文件名）
//    http://localhost:8088/download?fullFileName=2022/12/1/cva3f675d9-ed7e-46ac-97bf-4fd9bdc6ba62.pdf&fileName=WEB.pdf
    @GetMapping("/download")
    public R downloadFile(String fullFileName, String fileName, final HttpServletResponse response,
                          final HttpServletRequest request) {
        OutputStream os = null; //输出流
        InputStream is = null; //输入流
        if(StringUtil.isEmpty(fileName)){fileName="下载";}
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            System.out.println(URLDecoder.decode(fileName, "UTF-8"));
            // 读取流
            String realPath = path + URLDecoder.decode(fullFileName, "UTF-8");
            File f = new File(realPath);
            System.out.println(f.exists());
            is = new FileInputStream(f);
            // 复制
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
            return R.err().put("message", "下载附件失败,error:" + e.getMessage());
        }
        // 文件的关闭放在finally中
        finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
}